require('babel-core/register')({
  presets: ['es2015-node5', 'stage-3']
});

const Koa = require('koa');
const app = new Koa();

const cors = require('koa2-cors');

const process = require('child_process');

const bodyParser = require('koa-bodyparser');

const router = require('koa-router')({});

const routerHandler = require('./app/Routes/web');

const JiraService = require('./app/Services/JiraService');

const JiraProcess = require('./app/Services/JiraProcess');


/**
 * 开启一个子进程用于定时从Jira服务器中获取数据，并保存到数据库；
 * 在子进程出现异常断开或退出时，自动重启进程。
 */
let jira_process = process.fork(JiraProcess, { silent: true });

jira_process.on('diconnect', function () {
  jira_process.kill();
  jira_process = process.fork(JiraProcess, { silent: true });
});

jira_process.on('exit', function () {
  jira_process = process.fork(JiraProcess, { silent: true });
});

/**
 * 通用请求异常处理
 */
app.use(async (ctx, next) => {
  try {
    await next();
    console.log(`api--->${ctx.method} ${ctx.url}`);
  } catch (err) {
    console.log('error --->')
    console.log(err)
    ctx.body = {
      code: -1,
      message: '出现未知错误!'
    }
  }
});

app.use(bodyParser());

/**
 * 通用请求响应格式
 */
app.use(async function (ctx, next) {
  ctx.constantResData = function (CONSTANTDATA, data = {}) {
    return {
      ...CONSTANTDATA,
      data: data
    }
  }
  await next();
});

routerHandler(router);

app.use(cors());

app.use(router.routes())
  .use(router.allowedMethods());

app.listen(3000);